﻿using Chromium;
using M5.GeminiHybird.Core.Attribute;
using M5.GeminiHybird.Core.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace M5.GeminiHybird.Core.Builder
{
    internal class SchemeBuilder
    {

        internal void Config()
        {
            var factory = new CfxSchemeHandlerFactory();
            factory.Create += XHR.SchemeHandlerFactorCreateEvent.RequestEvent;

            SchemeConfig config = SchemeConfig.Instance;

            CfxRuntime.RegisterSchemeHandlerFactory(config.Name, config.Domain, factory);

            Assembly exeAssem = Assembly.GetEntryAssembly();
            List<Type> executeClassTypes = new List<Type>();
            List<Type> allTypes = new List<Type>(exeAssem.GetTypes());

            var allAssembly = Assembly.GetEntryAssembly().GetReferencedAssemblies();

            string[] notSearchAssembly = new string[] {
                "mscorlib", "System","System.Windows.Forms","System.Drawing"
            };
            foreach (var assem in allAssembly)
            {
                if (notSearchAssembly.Contains(assem.Name))
                {
                    continue;
                }
                Type[] tts = Assembly.Load(assem.FullName).GetTypes();
                allTypes.AddRange(tts);
            }
            foreach (Type tChild in allTypes)
            {
                if (tChild.BaseType == typeof(XHR.Controller.BaseController))
                {
                    executeClassTypes.Add(tChild);
                }
            }

            foreach (var executeType in executeClassTypes)
            {
                string typeName = executeType.Name.ToLower();
                typeName = typeName.Remove(typeName.LastIndexOf("controller"));

                object instanceObj = executeType.Assembly.CreateInstance(executeType.FullName);
                var baseController = (instanceObj as XHR.Controller.BaseController);

                var methods = instanceObj.GetType().GetMethods();
                foreach (var method in methods)
                {
                    if (!ControllerMethodAttribute.HasThisAttribute(method))
                        continue;

                    string methodName = $"{typeName}/{method.Name.ToLower()}";

                    //XHR.Routes.RawUrlAndCSharpMethodPairs.Add($"{typeName}/{method.Name.ToLower()}", $"{executeType.FullName}.{method.Name}");
                    if (!XHR.Routes.RawUrlAndControllerPairs.ContainsKey(methodName))
                        XHR.Routes.RawUrlAndControllerPairs.Add(methodName, baseController);
                }
            }
        }
    }
}
